package Thread_Synchronized_Lock;

public class Thread_生产和消费 {

	public static void main(String[] args) {
		Goods g=new Goods();
		Produce p=new Produce(g);
		Consum c=new Consum(g);
		new Thread(p).start();
		new Thread(c).start();
	}

}

class Goods {
	private int index=0;
	char data[]=new char[6];
	public synchronized void produce(char c){
		if(index==6){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		data[index]=c;
		index++;
		this.notify();
	}
	
	public synchronized char consum() {
		if(index==0){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		index--;
		this.notify();
		return data[index];
	}
	
}

class Produce implements Runnable {
	Goods g;
	public Produce(Goods g) {
		this.g=g;
	}
	public void run(){
		for(int i=0;i<20;i++) {
			char c=(char) (Math.random()*26+'A');
			g.produce(c);
			System.out.println("生产了一个："+c);
			try {
				Thread.sleep((long) (Math.random()*1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
class Consum implements Runnable {
	Goods g;
	public Consum(Goods g) {
		this.g=g;
	}
	public void run(){
		for(int i=0;i<20;i++){
			char consum = g.consum();
			System.out.println("消费了一个："+consum);
			try {
				Thread.sleep((long) (Math.random()*1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}